/**
 * 
 */
package instant.mail;

import javax.mail.internet.InternetAddress;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.Toast;

/**
 * @author qiangli
 * 
 */
public class SetupActivity extends TabActivity {

	private class SendTask extends AsyncTask<Void, Void, Object> {

		@Override
		protected Object doInBackground(Void... params) {
				try {
					Email.test(SetupActivity.this);
					return null;
				} catch (Exception e) {
					return e;
				}
		}

		@Override
		protected void onCancelled() {
			try {
				dismissDialog(DIALOG_PROGRESS_SENDING);
			} catch (Exception e) {
			}
		}

		@Override
		protected void onPreExecute() {
			showDialog(DIALOG_PROGRESS_SENDING);
		}

		@Override
		protected void onPostExecute(Object result) {
			try {
				dismissDialog(DIALOG_PROGRESS_SENDING);
			} catch (Exception e) {
			}
			if (result == null) {
				Toast.makeText(SetupActivity.this, R.string.msg_test_ok, Toast.LENGTH_SHORT)
				.show();
				return;
			} 
			
			Throwable e = (Throwable) result;
			Toast.makeText(SetupActivity.this, e .getLocalizedMessage(), Toast.LENGTH_LONG)
			.show();
		}
	}
	
	private class MyTextWatcher implements TextWatcher {
		public void afterTextChanged(Editable edit) {
			toggleTestButton();
		}

		public void beforeTextChanged(CharSequence edit, int start, int count,
				int after) {
		}

		public void onTextChanged(CharSequence edit, int start, int before,
				int count) {
		}	
	}

	public static final String EXTRA_TAB = "instant.mail.extra.tab";

	public static final int TAB_ACCOUNT = 0;
	public static final int TAB_SMTPSERVER = 1;
	public static final int TAB_SIGNATURE = 2;
	
	private static final int MENU_DONE = 1;
	private static final int DIALOG_PROGRESS_SENDING = 1;

	private static final int DIALOG_PASSWORD_CLEARTEXT = 2;

	private MenuItem doneMenuItem;
	private ProgressDialog sendProgressDialog;
	private Button testBtn;
	private Button doneBtn;
	private EditText email;
	private EditText username;
	private EditText password;
	private EditText nickname;
	private EditText replyto;

	private boolean usernameWasEmpty;

	private Dialog passwordDialog;

	private EditText cleartext;

	private void loadPreference() {
		final SharedPreferences p = PreferenceManager
				.getDefaultSharedPreferences(this);

		email = (EditText) findViewById(R.id.setup_email);
		email.setText(p.getString(Preferences.EMAIL, Preferences.GMAIL_DOMAIN));
		
		username = (EditText) findViewById(R.id.setup_username);
		username.setText(p.getString(Preferences.USERNAME, ""));
		
		password = (EditText) findViewById(R.id.setup_password);
		password.setText(p.getString(Preferences.PASSWORD, ""));
		
		nickname = (EditText) findViewById(R.id.setup_nickname);
		nickname.setText(p.getString(Preferences.NICKNAME, ""));
		
		replyto = (EditText) findViewById(R.id.setup_replyto);
		replyto.setText(p.getString(Preferences.REPLYTO, ""));
		//
		EditText host = (EditText) findViewById(R.id.setup_host);
		host.setText(p.getString(Preferences.HOST, Preferences.DEFAULT_HOST));
		EditText port = (EditText) findViewById(R.id.setup_port);
		port.setText(p.getString(Preferences.PORT, Preferences.DEFAULT_PORT));
		CheckBox starttls = (CheckBox) findViewById(R.id.setup_starttls);
		starttls.setChecked(p.getBoolean(Preferences.STARTTLS_ENABLE, true));
		//
		EditText sig = (EditText) findViewById(R.id.setup_signature);
		sig.setText(p.getString(Preferences.SIGNATURE, ""));
		CheckBox loc = (CheckBox) findViewById(R.id.setup_mylocation);
		loc.setChecked(p.getBoolean(Preferences.SIGNATURE_LOCATION, false));
		CheckBox time = (CheckBox) findViewById(R.id.setup_mytime);
		time.setChecked(p.getBoolean(Preferences.SIGNATURE_TIME, false));
		EditText pic = (EditText) findViewById(R.id.setup_mypicture);
		pic.setText(p.getString(Preferences.SIGNATURE_PHOTO, ""));
		//
		initAutofill();
	}

	private void initAutofill() {
		//copy and auto fill username
		TextWatcher ew = new MyTextWatcher() {
			public void afterTextChanged(Editable edit) {
				super.afterTextChanged(edit);
				//
				String s = email.getText().toString();
				int idx = s.indexOf("@");
				//clear if no @, user may have backspace'd
				if (idx <= 0 && usernameWasEmpty) {
					username.setText("");
					return;
				}
				//auto fill
				if (idx > 0 && usernameWasEmpty) {
					username.setText(s.substring(0, idx));
					return;
				}
			}
		};
		email.addTextChangedListener(ew);
		//
		TextWatcher uw = new MyTextWatcher() {
			public void afterTextChanged(Editable edit) {
				super.afterTextChanged(edit);
				//
				String a = email.getText().toString();
				String s = username.getText().toString();
				usernameWasEmpty = (TextUtils.isEmpty(s) || a.startsWith(s));
			}
		};
		username.addTextChangedListener(uw);
		//
		TextWatcher pw = new MyTextWatcher();
		password.addTextChangedListener(pw);
	}

	private void toggleTestButton() {
		boolean enable = (isValidEmail(email) && username.length() > 0 && password.length() > 0);
		testBtn.setEnabled(enable);
	}

	private boolean isValidEmail(EditText email) {
		String s = email.getText().toString();
		if (Utils.isValidEmail(s) == false) {
			return false;
		}
		try {
			InternetAddress.parse(s);
			return true;
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		super.onCreate(savedInstanceState);
		//
		TabHost tabs = getTabHost();

		LayoutInflater.from(this).inflate(R.layout.setup,
				tabs.getTabContentView(), true);

		tabs.addTab(tabs.newTabSpec("tab1").setIndicator(
				getString(R.string.tab_account)).setContent(R.id.setup_tab1));
		tabs.addTab(tabs.newTabSpec("tab2").setIndicator(
						getString(R.string.tab_smtpserver)).setContent(
						R.id.setup_tab2));
		tabs.addTab(tabs.newTabSpec("tab3").setIndicator(
				getString(R.string.tab_signature)).setContent(R.id.setup_tab3));

		setTitle(R.string.app_setup);
		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.etalk25);
		//
		Button pwdBtn = (Button) findViewById(R.id.setup_password_button);
		pwdBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DIALOG_PASSWORD_CLEARTEXT);
			}
		});
		//
		Button prvBtn = (Button) findViewById(R.id.setup_preview);
		prvBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				doPreview();
			}
		});
		//
		testBtn = (Button) findViewById(R.id.setup_test);
		testBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				savePreference();
				//
				new SendTask().execute();
			}
		});

		doneBtn = (Button) findViewById(R.id.setup_done);
		doneBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				savePreference();
				finish();
			}
		});
		//
		int tab = getIntent().getIntExtra(EXTRA_TAB, 0);
		tabs.setCurrentTab(tab);
		loadPreference();
		toggleTestButton();
		//
		setResult(RESULT_OK);
		//
		usernameWasEmpty = (TextUtils.isEmpty(username.getText().toString()));
	}

	private void doPreview() {
		try {
			EditText se = (EditText) findViewById(R.id.setup_signature);
			String sig = trim(se.getText().toString());
			CheckBox loc = (CheckBox) findViewById(R.id.setup_mylocation);
			CheckBox time = (CheckBox) findViewById(R.id.setup_mytime);
			EditText pe = (EditText) findViewById(R.id.setup_mypicture);
			String pic = trim(pe.getText().toString());
			//
			WebView wv =  (WebView) findViewById(R.id.setup_webview);;
			String c = MailTemplate.formatSignature(this, true, 
					sig, loc.isChecked(), time.isChecked(), pic );
			wv.loadData(c, "text/html", "utf-8");
		} catch (Exception e) {
			//
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		 switch (id) {
         case DIALOG_PROGRESS_SENDING:
        	 sendProgressDialog = createSendProgressDialog();
        	 return sendProgressDialog;
         case DIALOG_PASSWORD_CLEARTEXT:
        	 passwordDialog = createPasswordDialog();
        	 return passwordDialog;
		 }
		 return null;
	}
	
	private Dialog createPasswordDialog() {
		 LayoutInflater li = LayoutInflater.from(this);
         final View v = li.inflate(R.layout.setup_password, null);
         cleartext = (EditText) v.findViewById(R.id.setup_password_cleartext);
         return new AlertDialog.Builder(this)
             .setView(v)
             .setTitle(R.string.button_password_cleartext)
             .setPositiveButton(R.string.button_confirm, new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int whichButton) {
                	 password.setText(cleartext.getText());
                 }
             })
             .setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int whichButton) {
                 }
             })
             .create();
	}

	private ProgressDialog createSendProgressDialog() {
		ProgressDialog pd = new ProgressDialog(this);
		pd.setMessage(getText(R.string.status_sending));
		pd.setIndeterminate(true);
		pd.setCancelable(false);
		return pd;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		doneMenuItem = menu.add(Menu.NONE, MENU_DONE, Menu.NONE,
				R.string.menu_done);
		doneMenuItem.setIcon(R.drawable.menu_save);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case MENU_DONE:
			savePreference();
			finish();
			return true;
		default:
		}
		return false;
	}
	
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	savePreference();
        	finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
    
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch(id) {
		case DIALOG_PASSWORD_CLEARTEXT:
			//cleartext.setText(password.getText());
			cleartext.setText(null);
			break;
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		doneMenuItem.setEnabled(true);
		return true;
	}

	private void savePreference() {
		final SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(this);
		SharedPreferences.Editor ed = pref.edit();

		//
		ed.putString(Preferences.EMAIL, trim(email.getText().toString()));
		//
		ed.putString(Preferences.USERNAME, trim(username.getText().toString()));
		//
		ed.putString(Preferences.PASSWORD, trim(password.getText().toString()));
		
		ed.putString(Preferences.NICKNAME, trim(nickname.getText().toString()));
		
		ed.putString(Preferences.REPLYTO, trim(replyto.getText().toString()));
		//
		EditText host = (EditText) findViewById(R.id.setup_host);
		ed.putString(Preferences.HOST, trim(host.getText().toString()));
		EditText port = (EditText) findViewById(R.id.setup_port);
		ed.putString(Preferences.PORT, trim(port.getText().toString()));
		CheckBox starttls = (CheckBox) findViewById(R.id.setup_starttls);
		ed.putBoolean(Preferences.STARTTLS_ENABLE, starttls.isChecked());
		//
		EditText sig = (EditText) findViewById(R.id.setup_signature);
		ed.putString(Preferences.SIGNATURE, trim(sig.getText().toString()));
		CheckBox loc = (CheckBox) findViewById(R.id.setup_mylocation);
		ed.putBoolean(Preferences.SIGNATURE_LOCATION, loc.isChecked());
		CheckBox time = (CheckBox) findViewById(R.id.setup_mytime);
		ed.putBoolean(Preferences.SIGNATURE_TIME, time.isChecked());
		EditText pic = (EditText) findViewById(R.id.setup_mypicture);
		ed.putString(Preferences.SIGNATURE_PHOTO, trim(pic.getText().toString()));
		//
		ed.commit();
	}

	private static String trim(String s) {
		if (s == null) {
			return "";
		}
		return s.trim();
	}
}
